import re

from  flask_shop.user import user,user_api
from flask import  request
from flask_shop import models,db
from flask_restful import Resource
from flask_shop.utils.message import to_dict_msg
from flask_shop.utils.tokens import g_token,v_toke,login_rq
import json


class User(Resource):
    def get(self):
        pass
    def post(self):
        # json_data = json.loads(request.get_data().decode('utf-8'))
        # print(json_data)
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        real_pwd = request.form.get('real_pwd')
        nick_name = request.form.get('nick_name')
        phone = request.form.get('phone')
        email = request.form.get('email')

        print(name,pwd,real_pwd)
        if not all([name,pwd,real_pwd]):
            return to_dict_msg(10000)
        if len(name)<2:
            return to_dict_msg(10011)
        if len(pwd)<2:
            return to_dict_msg(10012)
        if pwd!=real_pwd:
            return to_dict_msg(10013)
        if not re.match(r'1[345678]\d{9}',phone):
            return to_dict_msg(10014)
        if not re.match(r'^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$',email):
            return to_dict_msg(10015)

            #rid = int(request.form.get("role_name")) if request.form.get("role_name") else 0
        try:
            usr = models.User(uname = name,password=pwd,nick_name=nick_name,phone=phone,email=email)
            db.session.add(usr)
            db.session.commit()
            return {'status':200,'msg':'成功！'}
        except Exception:
            return to_dict_msg(20000)

user_api.add_resource(User,'/',endpoint='user')
@user.route("/",methods=['POST'])
def index():
    return  "hello 蓝图"

@user.route("/login",methods=['POST'])
@login_rq
def login():
    name = request.form.get('uname')
    pwd = request.form.get('pwd')
    print(name,pwd)
    if not all([name,pwd]):
        return {'status':10000,'msg':'数据不完整'}
    if len(name) >1:
        user = models.User.query.filter_by(uname=name).first()
        if user:
            if user.yanz(pwd):
                token=g_token(user.id,100000)
                v_toke(token)
                return to_dict_msg(200,data={'token':token})
    return {'stauts':10001,'msg':'用户名或密码错误'}